import { UploadOutlined } from "@ant-design/icons";
import { Button, Upload } from "antd";
import { useRef, useState } from "react";
import "./index.less";
import * as XLSX from "xlsx";

export default ({
  value,
  onChange,
  showUploadList = false,
  loading = false,
  type = "不同应力",
}) => {
  const fileRef = useRef(null);
  const [fileNames, setFileNames] = useState([]);

  const beforeUpload = () => {
    let files = fileRef.current.files;
    const fileNames = Array.from(files).map((item) => item.name);
    setFileNames(fileNames);
    if (files.length === 0) return;

    const postDataArr = [];
    const fileReader = new FileReader();
    fileReader.onload = (e) => {
      const arrayBuffer = e.target.result;
      const workbook = XLSX.read(arrayBuffer, {
        type: "array",
        cellDates: true,
        cellText: false,
      });
      const worksheet = workbook.Sheets[workbook.SheetNames[0]];
      const data = XLSX.utils.sheet_to_json(worksheet, {
        header: 1,
        raw: false,
        dateNF: "yyyy-mm-dd", // 设置读取的日期格式 raw: false,cellDates: true, cellText: false,必须同时设置
      });
      console.log("data===", data);
      data.slice(1).forEach((arr) => {
        postDataArr.push({
          rundate: arr[1],
          foamType: arr[2],
          stressForty: arr[3],
          weight: arr[4],
          density: arr[5],
          modulus: arr[6],
          compressStrain: arr[7],
          compressStress: arr[8],
          maxAxialForce: arr[9],
          oriAxialForce: arr[10],
          shearStrain: arr[11],
          shearStress: arr[12],
          maxTorque: arr[13],
          corAxialForce: arr[14],
          coefficient: arr[15],
          swellingQuality: arr[16], // 溶胀质量
          swellingRate: arr[17], // 溶胀率
          qualityAfterDrying: arr[18], // 干燥后质量
          qualityRatioAfterDrying: arr[19], // 干燥后质量比
          area: arr[20],
        });
      });
      onChange(postDataArr, files[0]);
    };
    fileReader.readAsArrayBuffer(files[0]); // 通过文件上传组件选择的文件
  };

  return (
    <div className="upload-container">
      <Button loading={loading} icon={<UploadOutlined />}>
        上传文件
      </Button>
      {loading ? null : (
        <input
          className="add-input"
          type="file"
          ref={fileRef}
          multiple={true}
          onChange={beforeUpload}
        />
      )}

      {showUploadList && fileNames.length ? (
        <ul>
          {fileNames.map((item) => (
            <li key={item}>{item}</li>
          ))}
        </ul>
      ) : null}
    </div>
  );
};
